<template>
  <div class="book-manage">
    <!-- 面包屑区域 -->
    <BreadCrumb>图书管理</BreadCrumb>
    <div class="content">
      <!-- 卡片区域 -->
      <el-card>
        <!-- 搜索与添加区域 row(行)和 col(列) 是栅格布局-->
        <el-row :gutter="20">
          <el-col :span="10">
            <el-input
              placeholder="Please input"
              size="large"
              v-model="input"
              class="input-with-select"
              @keydown.enter="searchBook"
            >
              <template #prepend>
                <el-select v-model="select" style="width: 150px">
                  <el-option label="图书编号" value="1" />
                  <el-option label="图书名称关键词" value="2" />
                  <el-option label="图书类别关键词" value="3" />
                  <el-option label="图书作者关键词" value="4" />
                </el-select>
              </template>
              <template #append>
                <el-button icon="el-icon-search" @click="searchBook" />
              </template>
            </el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" size="large" @click="AddDialogVisible = true">添加</el-button>
          </el-col>
        </el-row>
        <!-- 借阅历史列表区域 -->
        <el-table :data="data" border stripe>
          <el-table-column type="index" label="#" align="center"></el-table-column>
          <el-table-column prop="id" label="图书编号" align="center" width="100px" />
          <el-table-column prop="bookname" label="图书名称" align="center" width="150px" />
          <el-table-column prop="booktype" label="图书类别" align="center" width="90px" />
          <el-table-column prop="author" label="作者" align="center" width="100px" />
          <el-table-column prop="translator" label="译者" align="center" width="90px" />
          <el-table-column prop="publisher" label="出版社" align="center" width="160px" />
          <el-table-column prop="publish_time" label="出版时间" align="center" width="120px" />
          <el-table-column prop="price" label="价格" align="center" width="90px" />
          <el-table-column prop="stock" label="库存" align="center" width="90px" />

          <el-table-column label="操作" align="center">
            <!-- 作用域插槽，scope.row 可以拿到对应这一行的数据 -->
            <template #default="scope">
              <el-button
                type="success"
                size="default"
                @click="showEditDialog(scope.row)"
                :disabled="userStore.user.is_admin === 'is' ? false : true"
                >修改</el-button
              >
              <el-button
                type="danger"
                size="default"
                @click="deleteBook(scope.row)"
                :disabled="userStore.user.is_admin === 'is' ? false : true"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 添加图书的对话框 -->
    <el-dialog
      v-model="AddDialogVisible"
      title="添加图书"
      width="65%"
      draggable
      @close="addDialogClosed"
    >
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="80px" size="large">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图书 ID" prop="id">
              <el-input v-model.trim="addForm.id" />
            </el-form-item>
            <el-form-item label="图书名称" prop="bookname">
              <el-input v-model.trim="addForm.bookname" />
            </el-form-item>
            <el-form-item label="图书类别" prop="booktype">
              <el-input v-model.trim="addForm.booktype" />
            </el-form-item>
            <el-form-item label="作者" prop="author">
              <el-input v-model.trim="addForm.author" />
            </el-form-item>
            <el-form-item label="译者" prop="translator">
              <el-input v-model.trim="addForm.translator" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出版社" prop="publisher">
              <el-input v-model.trim="addForm.publisher" />
            </el-form-item>
            <el-form-item label="出版时间" prop="publish_time">
              <!-- <el-input v-model.trim="addForm.publish_time" /> -->
              <el-date-picker v-model="addForm.publish_time" type="date" placeholder="请选择时间" />
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input v-model="addForm.price" />
            </el-form-item>
            <el-form-item label="库存" prop="stock">
              <el-input v-model.number="addForm.stock" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="AddDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addBook(addFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改图书的对话框 -->
    <el-dialog
      v-model="EditDialogVisible"
      title="添加图书"
      width="65%"
      draggable
      @close="editDialogClosed"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
        size="large"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图书 ID">
              <el-input v-model.trim="editForm.id" disabled />
            </el-form-item>
            <el-form-item label="图书名称" prop="bookname">
              <el-input v-model.trim="editForm.bookname" />
            </el-form-item>
            <el-form-item label="图书类别" prop="booktype">
              <el-input v-model.trim="editForm.booktype" />
            </el-form-item>
            <el-form-item label="作者" prop="author">
              <el-input v-model.trim="editForm.author" />
            </el-form-item>
            <el-form-item label="译者" prop="translator">
              <el-input v-model.trim="editForm.translator" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出版社" prop="publisher">
              <el-input v-model.trim="editForm.publisher" />
            </el-form-item>
            <el-form-item label="出版时间" prop="publish_time">
              <!-- <el-input v-model.trim="addForm.publish_time" /> -->
              <el-date-picker
                v-model="editForm.publish_time"
                type="date"
                placeholder="请选择时间"
              />
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input v-model="editForm.price" />
            </el-form-item>
            <el-form-item label="库存" prop="stock">
              <el-input v-model.number="editForm.stock" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="EditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editBook(editFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useUserStore } from '@/store/userStore.js'
import BreadCrumb from '@/components/common/BreadCrumb.vue'
import { ElMessageBox } from 'element-plus'
import {
  getAllBooks,
  getBooksByNameKey,
  getBooksByTypeKey,
  getBooksByAuthorKey,
  addBookR,
  delBookById,
  getBookById,
  updateBook
} from '@/network/book.js'
import { onMounted, reactive, ref } from 'vue'
import { messageApi } from '../api/global'
import { checkBookBack } from '@/network/borrow.js'

//* 变量声明
const userStore = useUserStore()
let data = ref([]) // 读者信息数据
const select = ref('1') // 下拉选择
const input = ref('') // 文本输入框值 --
// 添加图书的变量
const AddDialogVisible = ref(false) // 添加图书对话框的显示和隐藏
const addFormRef = ref(null) // 添加图书的表单引用
// 添加图书的表单对象
const addForm = reactive({
  id: '',
  bookname: '',
  booktype: '',
  author: '',
  translator: '',
  publisher: '',
  publish_time: '',
  price: '',
  stock: ''
})
// 添加图书的表单规则
const addRules = reactive({
  id: [
    { required: true, message: '请输入图书编号', trigger: 'blur' },
    { min: 1, max: 10, message: '图书编号长度在1~10个字符之间', trigger: 'blur' }
  ],
  bookname: [
    { required: true, message: '请输入图书名称', trigger: 'blur' },
    { min: 1, max: 30, message: '图书名称长度在1~30个字符之间', trigger: 'blur' }
  ],
  booktype: [
    { required: true, message: '请输入图书类别', trigger: 'blur' },
    { min: 1, max: 10, message: '图书类别长度在1~10个字符之间', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入图书作者', trigger: 'blur' },
    { min: 1, max: 10, message: '图书作者长度在1~10个字符之间', trigger: 'blur' }
  ],
  translator: [
    { required: true, message: '请输入图书译者', trigger: 'blur' },
    { min: 1, max: 10, message: '图书译者长度在1~10个字符之间', trigger: 'blur' }
  ],
  publisher: [
    { required: true, message: '请输入出版社', trigger: 'blur' },
    { min: 1, max: 10, message: '出版社长度在1~10个字符之间', trigger: 'blur' }
  ],
  publish_time: [
    { required: true, message: '请输入出版日期', trigger: 'blur' }
    // { min: 1, max: 1, message: '出版日期长度在1~10个字符之间', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入图书价格', trigger: 'blur' },
    { min: 1, max: 9999, message: '请输入数字，图书价格在1~9999之间', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入图书库存', trigger: 'blur' },
    {
      type: 'number',
      min: 1,
      max: 9999,
      message: '请输入数字，图书库存在1~9999之间',
      trigger: 'blur'
    }
  ]
})
// 修改图书所需的变量
const EditDialogVisible = ref(false)
const editFormRef = ref(null)
let editForm = ref({})
const editRules = reactive({
  id: [
    { required: true, message: '请输入图书编号', trigger: 'blur' },
    { min: 1, max: 20, message: '图书编号长度在1~20个字符之间', trigger: 'blur' }
  ],
  bookname: [
    { required: true, message: '请输入图书名称', trigger: 'blur' },
    { min: 1, max: 30, message: '图书名称长度在1~30个字符之间', trigger: 'blur' }
  ],
  booktype: [
    { required: true, message: '请输入图书类别', trigger: 'blur' },
    { min: 1, max: 10, message: '图书类别长度在1~10个字符之间', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入图书作者', trigger: 'blur' },
    { min: 1, max: 10, message: '图书作者长度在1~10个字符之间', trigger: 'blur' }
  ],
  translator: [
    { required: true, message: '请输入图书译者', trigger: 'blur' },
    { min: 1, max: 10, message: '图书译者长度在1~10个字符之间', trigger: 'blur' }
  ],
  publisher: [
    { required: true, message: '请输入出版社', trigger: 'blur' },
    { min: 1, max: 10, message: '出版社长度在1~10个字符之间', trigger: 'blur' }
  ],
  publish_time: [
    { required: true, message: '请输入出版日期', trigger: 'blur' }
    // { min: 1, max: 1, message: '出版日期长度在1~10个字符之间', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入图书价格', trigger: 'blur' },
    { min: 1, max: 9999, message: '请输入数字，图书价格在1~9999之间', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入图书库存', trigger: 'blur' },
    {
      type: 'number',
      min: 0,
      max: 99999,
      message: '请输入数字，图书库存在0~99999之间',
      trigger: 'blur'
    }
  ]
})

//* 事件处理

// 获取所有读者信息
const getBooks = async () => {
  const { data: res } = await getAllBooks()
  // 处理时间
  res.data.forEach(item => {
    item.publish_time = new Date(item.publish_time).toLocaleDateString()
  })
  data.value = res.data
}

// 查询图书
const searchBook = async () => {
  // 图书编号查询
  if (select.value === '1') {
    if (input.value === '') return getBooks()
    const { data: res } = await getBookById(input.value)
    if (res.code !== 200) return messageApi('error', res.msg)
    data.value = []
    data.value.push(res.data)
  }
  // 图书名称查询
  if (select.value === '2') {
    const { data: res } = await getBooksByNameKey({ bookNameKey: input.value })
    if (res.code !== 200) return messageApi('error', '查询失败！')
    data.value = res.data
  }
  // 图书类型查询
  if (select.value === '3') {
    const { data: res } = await getBooksByTypeKey({ bookTypeKey: input.value })
    if (res.code !== 200) return messageApi('error', '查询失败！')
    data.value = res.data
  }
  // 图书作者查询
  if (select.value === '4') {
    const { data: res } = await getBooksByAuthorKey({ bookAuthorKey: input.value })
    if (res.code !== 200) return messageApi('error', '查询失败！')
    data.value = res.data
  }
}

// 添加图书
const addBook = async addFormRef => {
  await addFormRef.validate(async valid => {
    if (!valid) return
    if (!Number(addForm.price)) return messageApi('warning', '价格需要填入数字！')
    // 格式化出版日期
    addForm.publish_time = new Date(addForm.publish_time).toLocaleDateString()
    const { data: res } = await addBookR(addForm)
    if (res.code !== 200) return messageApi('error', res.msg)
    messageApi('success', res.msg)
    getBooks()
    AddDialogVisible.value = false
  })
}

// 监听图书对话框的关闭事件
const addDialogClosed = () => {
  addFormRef.value.resetFields()
}

// 删除图书
const deleteBook = async row => {
  try {
    await ElMessageBox.confirm(`确认删除该图书吗？`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 先检查该图书是否存在未归还
    const { data: backRes } = await checkBookBack(row.id)
    if (backRes.data) return messageApi('warning', '该图书仍有读者未归还，请归还图书再删除！')
    // 发起删除图书的请求
    const { data: res } = await delBookById(row.id)
    if (res.code !== 200) return messageApi('error', res.msg)
    messageApi('success', res.msg)
    getBooks()
  } catch (e) {
    messageApi('info', '已取消')
  }
}

// 显示修改图书的对话框
const showEditDialog = async row => {
  const { data: res } = await getBookById(row.id)
  editForm.value = res.data
  EditDialogVisible.value = true
}

// 确认修改图书
const editBook = async editFormRef => {
  await editFormRef.validate(async valid => {
    if (!valid) return
    // 判断价格是否为一个数字
    if (!Number(editForm.value.price)) return messageApi('warning', '价格需要填入数字！')
    // 发起修改图书的请求
    const { data: res } = await updateBook(editForm.value)
    if (res.code !== 200) return messageApi('error', res.msg)
    messageApi('success', res.msg)
    getBooks()
    EditDialogVisible.value = false
  })
}

// 监听修改图书对话框的关闭事件
const editDialogClosed = () => {
  editFormRef.value.resetFields()
}

onMounted(() => {
  getBooks()
})
</script>

<style lang="less" scoped>
.book-manage {
  height: 100%;
  width: 85%;
  background-color: #eaedf1;
}
.content {
  width: 100%;
  // height: 600px;
  margin: 0 15px;
  background: #fff;
  overflow: auto;
  width: 1300px;

  .el-card {
    width: 100%;
  }
  .el-table {
    width: 100%;
  }
  .el-row {
    margin-bottom: 10px;
  }
}

.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
</style>
